#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import socket   
import time   
import sys, os
import getopt
import array

def usage():
    print("""
sendfile [-n times] [-u unit] [-d delay] [-p port] file1 file2 ...
    """)

if __name__ == '__main__':   
    #addr_str = '127.0.0.1'
    addr_str = '127.0.0.1'
    port = 25000

    if len(sys.argv) == 1:
        usage()
        exit(0)

    starti = 0
    vlist = sys.argv[1:]

    opts, args = getopt.getopt( 
            vlist[starti:],
            "vhn:d:p:r:u:",
            [
                "help", "verbose"
                ]
                                
            )

    repeat_n = 1
    delay_time = 0.1
    send_unit = 512

    for o, a in opts:
        if o == '-v':
            verbose = True
        elif o == '-h':
            usage()
            sys.exit(0)
        elif o in ('-n'):
            repeat_n = int(a)
        elif o == '-d':
            delay_time = float(a)
        elif o == '-u':
            send_unit = int(a)
        elif o == '-p':
            port = int(a)
        elif o == '-r':
            addr_str == a
        else:
            pass


    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    #sock.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)  
    addr = (addr_str, port)

    for filename in args:
        with open(filename) as f:
            buf = f.read()
            buf_len = len(buf)
            for i in range(repeat_n):
                print("Sending file %s for %d time"%(filename, i))
                start = 0
                size = send_unit
                while start < buf_len:
                    if start + send_unit > buf_len:
                        size = buf_len - start
                    else:
                        size = send_unit
                    sock.sendto(bytes(buf[start:start+size].encode('utf-8')), addr)
                    if delay_time > 0.01:
                        time.sleep(delay_time)
                    start = start + size

